/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tesam.gedeon.controller;

import com.tesam.gedeon.entity.Network;
import com.tesam.gedeon.entity.Provider;
import com.tesam.gedeon.entity.TrafficType;
import com.tesam.gedeon.service.NetworkService;
import com.tesam.gedeon.service.ProviderService;
import com.tesam.gedeon.service.TrafficTypeService;
import com.tesam.gedeon.util.Util;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.primefaces.json.JSONArray;
import org.primefaces.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Sistema
 */
@Controller
public class TrafficTypeController {

    @Autowired
    SystemUserController system;
    @Autowired
    TrafficTypeService trafficTypeService;
    @Autowired
    ProviderService providerService;
    @Autowired
    NetworkService networkService;

    Network network = new Network();
    Provider provider = new Provider();
    
    @RequestMapping(value = "/mediationtraffictype/index")
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("/mediationtraffictype/index");

        system.loadDataSystem(mv, request);
        String module = request.getParameter("module");
        if (!Util.isNullOrEmpty(module)) {
            request.getSession().setAttribute("module", module);
        }

        return mv;
    }

    @RequestMapping(value = "/mediationtraffictype/new")
    public ModelAndView newTrafficType(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("/mediationtraffictype/new");

        system.loadDataSystem(mv, request);
        request.getSession().setAttribute("tokenService", 1);
        mv.addObject("provider", providerService.getAll());

        mv.addObject("network", networkService.getListAll());

        return mv;

    }

    @RequestMapping(value = "/mediationtraffictype/newsave", method = RequestMethod.POST)
    public ModelAndView newsaveTrafficType(@ModelAttribute("TrafficType") TrafficType trafficType, HttpServletRequest request) {

        //ModelAndView mv = new ModelAndView("/mediationtraffictype/new");

        String message = null;

        ModelAndView mv = new ModelAndView("redirect:/mediationtraffictype/index");

        String token = (request.getSession().getAttribute("tokenTraffictype") == null) ? "" : request.getSession().getAttribute("tokenTraffictype").toString();

        if (token == null || token.isEmpty()) {
            System.out.println("Entro aqui");
            system.loadDataSystem(mv, request);

            return mv;
        } else {
            System.out.println("Entro aqui");
            trafficType.setCreatedBy(Integer.parseInt(request.getParameter("createdBy")));
            Provider provider = new Provider();
            provider.setId(Integer.parseInt(request.getParameter("CboProvider")));
            trafficType.setProvider(provider);
            Network network = new Network();
            network.setId(Integer.parseInt(request.getParameter("CboNetwork")));
            trafficType.setNetwork(network);

            System.out.println(trafficType.getCode());
            if (trafficTypeService.save(trafficType) > 0) {

                request.getSession().removeAttribute("tokenTraffictype");

                mv = new ModelAndView("/mediationtraffictype/index");

                message = "<div class=\"alert alert-block alert-success fade in\">"
                        + "<button class=\"close\" data-dismiss=\"alert\"></button>"
                        + "<strong>Éxito! </strong>"
                        + " Traffictype " + trafficType.getSubCode() + " registrado correctamente"
                        + "</div>";

                mv.addObject("message", message);

            } else {

                message = "<div class=\"alert alert-block alert-error fade in\">"
                        + "<button class=\"close\" data-dismiss=\"alert\"></button>"
                        + "<strong>Fallo! </strong>"
                        + " Ocurrio un error al tratar de registrar Traffictype" + trafficType.getSubCode() + " en el servidor"
                        + "</div>";

                mv.addObject("message", message);
            }
        }
        system.loadDataSystem(mv, request);
        return mv;

    }

    @RequestMapping(value = "/mediationtraffictype/update")
    public ModelAndView update(@ModelAttribute("TrafficType") TrafficType trafficType ,HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/mediationtraffictype/update");
        
        system.loadDataSystem(mv, request);
        mv.addObject("provider", providerService.getAll());
        
        mv.addObject("network", networkService.getListAll());
        
        mv.addObject("trafficType", trafficTypeService.getTrafficById(trafficType));
        
        return mv;
    }
    
    @RequestMapping(value = "/mediationtraffictype/saveUpdate")
    public ModelAndView saveUpdate(@ModelAttribute("TrafficType") TrafficType trafficType ,HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/mediationtraffictype/save");
                                                                   
        network.setId(Integer.parseInt(request.getParameter("CboNetwork").toString()));
        provider.setId(Integer.parseInt(request.getParameter("CboProvider").toString()));
        trafficType.setNetwork(network);
        trafficType.setProvider(provider);
        trafficTypeService.update(trafficType);
        
        mv.addObject("id", trafficType.getId());
        return mv;
    }
    
    @RequestMapping(value = "/mediationtraffictype/newsave")
    public ModelAndView saveNew(@ModelAttribute("TrafficType") TrafficType trafficType ,HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/mediationtraffictype/save");
        network.setId(Integer.parseInt(request.getParameter("CboNetwork").toString()));
        provider.setId(Integer.parseInt(request.getParameter("CboProvider").toString()));
        trafficType.setNetwork(network);
        trafficType.setProvider(provider);
        mv.addObject("id", trafficTypeService.save(trafficType));
        return mv;
    }
    
    @RequestMapping(value = "/mediationtraffictype/delete")
    public ModelAndView delete(@ModelAttribute("TrafficType") TrafficType trafficType ,HttpServletRequest request)
    {
        ModelAndView mv = new ModelAndView("/mediationtraffictype/delete");
        
        trafficTypeService.delete(trafficType);
        
        return mv ;
    }
    
    @RequestMapping(value = "/mediationtraffictype/view")
    public ModelAndView viewTrafficType(@ModelAttribute("TrafficType") TrafficType trafficType, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("/mediationtraffictype/view");

        mv.addObject("trafficType", trafficTypeService.getTrafficById(trafficType));
        
        system.loadDataSystem(mv, request);
        
        return mv ;
    }

    @RequestMapping(value = "/mediationtraffictype/ajax", method = RequestMethod.GET)
    public @ResponseBody
    String doAjaxGet() {

        int quantityrecord = 0;
        try {
            List<TrafficType> list = trafficTypeService.getListByLimit(0, 20, "tt.billingcode", "asc");

            // ArrayList<Cliente> list = clienteService.getAllClientes();
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();

            if (list.size() > 0) {
                for (TrafficType trafficType : list) {
                    JSONArray arrayPut = new JSONArray();
                    arrayPut.put(trafficType.getCode());
                    arrayPut.put(trafficType.getNetwork().getDescription());
                    arrayPut.put(trafficType.getProvider().getName());
                    arrayPut.put(trafficType.getProviderCode());
                    arrayPut.put(trafficType.getProviderName());
                    arrayPut.put(trafficType.getProviderSubName());
                    arrayPut.put(trafficType.getSubCode());
                    array.put(arrayPut);
                }
            }


            quantityrecord = trafficTypeService.getCountAll();
            json.put("iTotalRecords", quantityrecord);
            json.put("iTotalDisplayRecords", quantityrecord);
            json.put("aaData", array);

            return json.toString();
        } catch (Exception e) {
            System.out.print("Error - Controller-doAjax:" + e.getMessage());
        }

        return null;
    }

    @RequestMapping(value = "/mediationtraffictype/ajax", method = RequestMethod.POST)
    public @ResponseBody
    String doAjaxPost(HttpServletRequest request) {

        List<TrafficType> listTrafficType = null;
        int quantityrecord = 0;

        String[] columns = {"tt.billingcode", "net.description",
            "pr.name", "tt.providercode", "tt.providername", "tt.subcode", "tt.providerSubName",};

        String startLimit = request.getParameter("iDisplayStart");
        String endLimit = request.getParameter("iDisplayLength");
        String dataToSort = columns[Integer.valueOf(request
                .getParameter("iSortCol_0"))];
        String directionOfOrder = request.getParameter("sSortDir_0");
        String textSearch = request.getParameter("sSearch").toUpperCase();

        int _startLimit = 0;
        int _endLimit = 0;

        if (startLimit != null && !startLimit.equals("0")) {

            if (!startLimit.trim().isEmpty()) {
                _startLimit = Integer.valueOf(startLimit);
            }
        }

        if (endLimit != null && !endLimit.equals("0")) {
            if (!endLimit.trim().isEmpty()) {
                _endLimit = Integer.valueOf(endLimit);
            }
        }

        if (textSearch != null) {
            if (!textSearch.trim().isEmpty()) {
                textSearch = textSearch.trim();
                TrafficType trafficType = new TrafficType();
                trafficType.setProviderName(textSearch);
                listTrafficType = trafficTypeService.getListBySearch(_startLimit, _endLimit, dataToSort, directionOfOrder, trafficType);
                quantityrecord = trafficTypeService.getCountBySearch(trafficType);
                return trafficTypeService.getJsonDataFromArrayList(listTrafficType, quantityrecord);

            }
        }

        listTrafficType = trafficTypeService.getListByLimit(_startLimit, _endLimit, dataToSort, directionOfOrder);

        quantityrecord = trafficTypeService.getCountAll();

        return trafficTypeService.getJsonDataFromArrayList(listTrafficType, quantityrecord);
    }
}
